package com.beyond.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;


public class LoginCheckFilter implements Filter {
	/**
	 * 配置不验证是否登陆的do
	 */
	private Map<String, String> map = new HashMap<String, String>();
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		map.put("/forward/login", "jsp");
		map.put("/v1/login", "do");

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String source = httpRequest.getRequestURI();
		String contextPath = httpRequest.getContextPath();
		String reality = source.replace(contextPath, "");
		if(reality.indexOf("/resources") == 0){
			chain.doFilter(request, response);
			return;
		}
		
		if(StringUtils.isNotBlank(map.get(reality))){
			chain.doFilter(request, response);
			return;
		}
		HttpSession session = httpRequest.getSession();
		session.setMaxInactiveInterval(10*60*60);
		
		Object loginName = session.getAttribute("username");

		if (loginName == null) {
			HttpServletResponse httpServletResponse = (HttpServletResponse) response;
			PrintWriter out = httpServletResponse.getWriter();
			out.println("<html>");
			out.println("<head>");
			out.println("<script type='text/javascript'>");
			out.println("if(top.location.href != self.location.href){");
			out.println("   top.location ='" + contextPath+ "/forward/login'; ");
			out.println("} else {");
			out.println("   window.location.href='" + contextPath + "/forward/login';");
			out.println("}");
			out.println("</script></head><body></body></html>");
			return;
		}
		chain.doFilter(request, response);
	
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}
